uniform extern float4x4  gWorld;
uniform extern float4x4  gViewProj;
uniform extern float3    gEyePosW;
uniform extern float4    gColor;
uniform extern float3    gShieldCenterW;
uniform extern texture   gTex;
uniform extern float3    gHitPos;
uniform extern float     gHitElapsedTime;

sampler Tex = sampler_state
{
	Texture = <gTex>;
	MinFilter = LINEAR;
	MagFilter = LINEAR;
	MipFilter = LINEAR;
	AddressU  = CLAMP;
    AddressV  = CLAMP;
};

struct VSInput
{
    float3 posL    : POSITION0;
    float3 normalL : NORMAL0;
    float2 texc    : TEXCOORD0;
};

struct VSOutput
{
  float4 posH    : POSITION0;
  float3 normalW : TEXCOORD0;
  float3 posW    : TEXCOORD1;
  float2 texc    : TEXCOORD2;
  float3 color   : COLOR0;
};

VSOutput ShieldVS(VSInput input)
{
    VSOutput output;

	output.posW = mul(float4(input.posL, 1.0f), gWorld);
	
	output.normalW = normalize(output.posW - gShieldCenterW);
	
	output.posH = mul(float4(output.posW, 1.0f), gViewProj);
	output.texc = input.texc;
	
	float hitDist = length(output.posW - gHitPos);
	float magicNumber = 2500.0f; // depends on shield size
	if(gHitElapsedTime > 0.0f && hitDist < magicNumber) // magic number!!!
	{
		float greenBlueFactor = (hitDist / magicNumber);
		greenBlueFactor = greenBlueFactor * greenBlueFactor;
		output.color = float3(1.0f, greenBlueFactor, greenBlueFactor);
	}
	else
		output.color = float3(1.0f, 1.0f, 1.0f);

    return output;
}

float4 ShieldPS(VSOutput input) : COLOR0
{
    float3 eyeDirW = normalize(gEyePosW - input.posW);
    float surfaceToEye = max(dot(normalize(input.normalW), eyeDirW), 0.0f);
    if(surfaceToEye < 0.3f)
    {
		surfaceToEye = 0.3f + (0.3f - (surfaceToEye))*2.33f;
		//return float4(1,0,0,1);	
	}
    //float3 color = tex2D(Tex, input.texc).rgb*0.0f + gColor;
	float3 color = float3(1.0f,1.0f,1.0f);
    return float4(input.color, pow((1.0f - surfaceToEye),2)*gColor.a*2.0f);
}

technique Shield
{
    pass Pass1
    {
        AlphaBlendEnable = true;
        SrcBlend = SrcAlpha;
        DestBlend = InvSrcAlpha;
		ZWriteEnable = false;

        VertexShader = compile vs_1_1 ShieldVS();
        PixelShader = compile ps_2_0 ShieldPS();
    }
}
